package com.itshidu.jiaowu.util.freemarker

import com.alibaba.fastjson.JSON
import freemarker.core.Environment
import freemarker.template.TemplateDirectiveBody
import freemarker.template.TemplateDirectiveModel
import freemarker.template.TemplateException
import freemarker.template.TemplateModel
import groovy.json.JsonSlurper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.util.StringUtils

@Component
class AssetsTag implements TemplateDirectiveModel {

    @Autowired ResData resData
    def jsonSlurper = new JsonSlurper()

    @SuppressWarnings("rawtypes")
    @Override
    void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        //获取标签参数值  <@Res name="/test"> </@perm>
        //println(JSON.toJSONString(resData))
        def res = jsonSlurper.parseText(JSON.toJSONString(resData.res))
        println(res)
        Writer out = env.getOut()
        String t= params.get("name").toString()
        String[] names = t.trim().split(" ")
        for (String name : names) {
            if(StringUtils.isEmpty(name)||res[name]==null)continue
            if (res[name] instanceof String) {
                out.println( to(res[name]) )
            }
            if (res[name] instanceof Map) {
                res[name].each { k,v ->
                    out.println( to( v ) )
                }
            }

        }

    }


    def to(url) {
        if (url.endsWith(".js")) {
            return "<script src=\""+url+"\"></script>"
        }
        if (url.endsWith(".css")) {
            return "<link href=\""+url+"\" rel=\"stylesheet\">"
        }
    }

}